package sparkcore.day7.lesson06

import java.util.Properties

import org.apache.spark.{SparkConf, SparkContext}
import org.apache.spark.sql.{DataFrame, SQLContext}

/**
  * Created by Administrator on 2018/5/3.
  */
object UDFTest {
  def main(args: Array[String]): Unit = {
    val conf = new SparkConf().setMaster("local").setAppName("test")
    val sc = new SparkContext(conf)
    val sqlContext = new SQLContext(sc)

    sqlContext.udf.register("strLen",(username:String) =>{
      if(username != null){
        username.length
      }else{
        0
      }
    })

    val url="jdbc:mysql://hadoop1:3306/test"
    val table_name="user"
    val properties = new Properties()
    properties.put("user","aura")
    properties.put("password","aura")
    val df: DataFrame = sqlContext.read.jdbc(url,table_name,properties)

    df.createOrReplaceTempView("user")
    sqlContext.sql("select strLen(username) from user").show()
  }

}
